package com.sx.manage.controller.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sx.manage.controller.base.MBaseController;
import com.sx.manage.service.file.MConsumerCertificateWebServiceImpl;
import com.sx.manage.servlet.ViewAndModel;
import com.sx.manage.util.ImageUtils;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.manage.mybatis.form.file.MCertificateAddressForm;
import com.sx.model.manage.mybatis.vo.file.MCertificateAddressVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.result.ResultUploadVO;

/**
 * 证件类型地址controller
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/consumer/certificate")
public class MConsumerCertificateController extends MBaseController {
	/**
	 * 日志
	 */
	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Resource(name="consumerCertificateWebServiceImpl")
	private MConsumerCertificateWebServiceImpl consumerCertificateWebServiceImpl;
	/** 跳转到证件上传界面**/
	@RequestMapping(value = "/certificate/index/{consumer_id}")
	public ViewAndModel certificate_index(@PathVariable Long consumer_id) {
		log.info("跳转到证件上传界面");
		return consumerCertificateWebServiceImpl.certificate_index(new ViewAndModel(request, cache),consumer_id);
	}
	/** 跳转到证件上传界面**/
	@RequestMapping(value = "/certificate/toAdd/{consumer_id}")
	public ViewAndModel certificate_toAdd(@PathVariable Long consumer_id) {
		log.info("跳转到证件上传界面");
		return consumerCertificateWebServiceImpl.certificate_toAdd(new ViewAndModel(request, cache),consumer_id);
	}
	/** 跳转到证件上传界面**/
	@RequestMapping(value = "/certificate/toEdit/{id}")
	public ViewAndModel certificate_toEdit(@PathVariable Long id) {
		log.info("跳转到证件上传界面");
		return consumerCertificateWebServiceImpl.certificate_toEdit(new ViewAndModel(request, cache),id);
	}
	/**保存证件信息*/
	@RequestMapping(value = "/certificate/save")
	@ResponseBody
	public ResultBooleanVO certificate_save(@RequestBody MCertificateAddressForm form) {
		log.info("保存证件地址信息form={}",form);
		return consumerCertificateWebServiceImpl.certificate_save(form,this.loginConsumer());
	}
	/**保存证件信息*/
	@RequestMapping(value = "/certificate/update")
	@ResponseBody
	public ResultBooleanVO certificate_update(@RequestBody MCertificateAddressForm form) {
		log.info("保存证件地址信息form={}",form);
		return consumerCertificateWebServiceImpl.certificate_update(form,this.loginConsumer());
	}
	/**查询分页数据列表*/
	@RequestMapping("/certificate/page")
	@ResponseBody
	public ResultListVO<MCertificateAddressVO> certificate_page(MCertificateAddressForm form) {
		log.info("查询分页数据列表form={}",form);
		return consumerCertificateWebServiceImpl.certificate_page(form);
	}
	/**图片上传*/
	@RequestMapping(value = "/certificate/upload")
	@ResponseBody
	public ResultUploadVO<String> upload(@RequestParam(value = "files", required = false) MultipartFile file, HttpServletRequest request) {
		log.info("证件图片上传file={}",file);
		 ResultUploadVO<String> vo = consumerCertificateWebServiceImpl.upload(file, request);
		//上传文件 返回路径
		String oldPath = consumerCertificateWebServiceImpl.UploadFile(file, request);
		File img = new File(oldPath);
		try {
			FileOutputStream fos = new FileOutputStream(MSystemConstants.CERTIMAGEFACE_NEW_PATH+img.getName());
			ImageUtils.thumbnail(img, 450, 280, fos);
		} catch (Exception e) {
			log.info("文件压缩时异常error={}",e);
		}
		 String str = ImageUtils.ImageToBase64ByLocal(MSystemConstants.CERTIMAGEFACE_NEW_PATH+img.getName());
		 log.info("查询分页数据列表oldPath={}",oldPath);
		 vo.setCertimageface(str);
		return vo;
	}
	/***
     * 上传图片到服务器 并压缩
     *
     * @param myFile  文件
     * @param request
     * @return
     */
	public String UploadFile(MultipartFile myFile, HttpServletRequest request) {
		InputStream is = null;
        FileOutputStream fs = null;
        String filePath = null;
        /** 临时文件夹*/
        String imgPath = "xyimages" + File.separator + "buttonImgTemp" + File.separator;
        String tempPath = MSystemConstants.CERTIMAGEFACE_OLD_PATH + imgPath;
        log.info("old-path-{}",tempPath);
        File oldFile = new File(tempPath);
        if (!oldFile.exists()) {
            oldFile.mkdirs();
        }
        /** 处理后文件夹*/
        String newImaPath = "xyimages" + File.separator + "buttonImg" + File.separator;
        String newPath = MSystemConstants.CERTIMAGEFACE_OLD_PATH + newImaPath;
        log.info("new-path-{}",newPath);
        File newFile = new File(newPath);
        if (!newFile.exists()) {
            newFile.mkdirs();
        }
        try {
            /** 先存取源文件*/
            is = myFile.getInputStream();
            fs = new FileOutputStream(tempPath + myFile.getOriginalFilename());
            //...
            if (myFile.getSize() > 0) {
                byte[] buffer = new byte[1024 * 1024];
               // int bytesum = 0;
                int byteread = 0;
                while ((byteread = is.read(buffer)) != -1) {
                    //bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                    fs.flush();
                }
                fs.close();
                is.close();
            }
            /** 处理源文件 ，进行压缩再放置到新的文件夹*/
            filePath = tempPath + myFile.getOriginalFilename();
            log.info("filePath:{}",filePath);
        } catch (Exception ex) {
        	log.info("上传身份证、创建文件时异常error={}",ex);
        }
        return filePath;
    } 

}
